//
//  TYSearchBar.m
//  TYUIKit
//
//  Created by TuyaInc on 2019/2/1.
//

#import "TYSearchBar.h"

#import <objc/runtime.h>

#if __has_include("Masonry.h")
#import "Masonry.h"
#elif __has_include(<Masonry/Masonry.h>)
#import <Masonry/Masonry.h>
#endif

#import "NSObject+TYUIKitSwizzler.h"
#import "UIColor+TYCategory.h"
#import "TYSearchBarAppearance.h"

#import "TYIQKeyboardManagerDisableProtocol.h"
//#import "TYTheme.h"
static NSString * const kTYSearchBarTextFieldKVCKey = @"searchField";
static NSString * const kTYSearchBarCancelButtonKVCKey = @"cancelButton";

@interface TYSearchBar ()

@property (nonatomic, weak) UIView *ty_searchContainer;
@property (nonatomic, weak) UITextField *ty_textField;
@property (nonatomic, weak) UIButton *ty_cancelButton;

@property (nonatomic, strong) UIImageView *separatorImageview;

@end

@implementation TYSearchBar
@dynamic ty_active;
@dynamic delegate;
@dynamic ty_seperatorColor;

+ (void)load {
    Class<TYIQKeyboardManagerDisableProtocol> cls = NSClassFromString(kIQKeyboardManagerClassName);
    if (cls && [cls respondsToSelector:@selector(sharedManager)]) {
        id<TYIQKeyboardManagerDisableProtocol> target = [cls sharedManager];
        if ([target respondsToSelector:@selector(disabledDistanceHandlingClasses)]) {
            [target.disabledDistanceHandlingClasses addObject:self];
        }
        if ([target respondsToSelector:@selector(disabledTouchResignedClasses)]) {
            [target.disabledTouchResignedClasses addObject:self];
        }
    }
    
    if (@available(iOS 13.0, *)) {
        // ios13无法在searchbar的layoutsubview中修改textfield的frame
        NSString *clsName = [NSString stringWithFormat:@"_%@%@%@", @"UISearchBar", @"Search", @"ContainerView"];
        Class searchCotainerCls = NSClassFromString(clsName);
        [searchCotainerCls ty_uikit_swizzleSEL:@selector(layoutSubviews) withSEL:@selector(ty_swiz_searchContainerLayoutSubviews) fromClass:self];
    }
}

- (instancetype)init {
    if (self = [super init]) {
        [self initial];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initial];
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initial];
    }
    return self;
}

- (void)initial {
    self.backgroundImage = [UIImage new];
    self.backgroundColor = [TYSearchBarAppearance appearance].backgroundColor;
    self.tintColor = [TYSearchBarAppearance appearance].tintColor;
    self.placeholder = [TYSearchBarAppearance appearance].placeholder;
    self.translucent = [TYSearchBarAppearance appearance].translucent;
    self.searchTextPositionAdjustment = [TYSearchBarAppearance appearance].searchTextOffset;
    self.ty_separatorColor = [TYSearchBarAppearance appearance].separatorColor;
    self.ty_textFieldInsets = [TYSearchBarAppearance appearance].searchFieldInsets;
    self.ty_cancelButtonInsets = [TYSearchBarAppearance appearance].cancelButtonInsets;
    self.accessibilityIdentifier = [TYSearchBarAppearance appearance].searchAccessibilityIdentifier;
}

- (void)setupTextField {
    if (_ty_textField) {
        _ty_textField.tag = 1001;
        if ([TYSearchBarAppearance appearance].searchFieldBackgroundColor) {
            _ty_textField.backgroundColor = [TYSearchBarAppearance appearance].searchFieldBackgroundColor;
        }
        if ([TYSearchBarAppearance appearance].searchTextColor) {
            _ty_textField.textColor = [TYSearchBarAppearance appearance].searchTextColor;
        }
        if ([TYSearchBarAppearance appearance].searchTextFont) {
            _ty_textField.font = [TYSearchBarAppearance appearance].searchTextFont;
        }
        if ([TYSearchBarAppearance appearance].searchFieldCorner >= 0) {
            _ty_textField.layer.cornerRadius = [TYSearchBarAppearance appearance].searchFieldCorner;
        }
        _ty_textField.layer.masksToBounds = YES;
    }
}

#pragma mark - Override
- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self ty_layoutTextField];
    [self ty_layoutCancelButton];
}

- (void)ty_swiz_searchContainerLayoutSubviews {
    [self ty_swiz_searchContainerLayoutSubviews];
    
    UIView *view = self;
    UISearchBar *searchBar;
    while (searchBar == nil && view.superview) {
        if ([view.superview isKindOfClass:[UISearchBar class]]) {
            searchBar = (UISearchBar *)view.superview;
        }
        view = view.superview;
    }
    
    if ([searchBar respondsToSelector:@selector(ty_layoutTextField)]) {
        [searchBar performSelector:@selector(ty_layoutTextField)];
    }
    if ([searchBar respondsToSelector:@selector(ty_layoutCancelButton)]) {
        [searchBar performSelector:@selector(ty_layoutCancelButton)];
    }
}

- (void)ty_layoutTextField {
    if (!_ty_textField) {
        _ty_textField = [self valueForKey:kTYSearchBarTextFieldKVCKey];
        [self setupTextField];
    }
    
    if (_ty_textField && !UIEdgeInsetsEqualToEdgeInsets(_ty_textFieldInsets, UIEdgeInsetsZero)) {
        CGRect frame = _ty_textField.frame;
        frame = UIEdgeInsetsInsetRect(frame, _ty_textFieldInsets);
        _ty_textField.frame = frame;
    }
}

- (void)ty_layoutCancelButton {
    if (!_ty_cancelButton) {
        _ty_cancelButton = [self valueForKey:kTYSearchBarCancelButtonKVCKey];
        if (_ty_cancelButton) {
            _ty_cancelButton.tag = 1002;
            _ty_cancelButton.accessibilityIdentifier = [TYSearchBarAppearance appearance].cancelAccessibilityIdentifier;
            
            if ([TYSearchBarAppearance appearance].cancelButtonNormalColor) {
                [_ty_cancelButton setTitleColor:[TYSearchBarAppearance appearance].cancelButtonNormalColor forState:UIControlStateNormal];
            }
            if ([TYSearchBarAppearance appearance].cancelButtonHighlightColor) {
                [_ty_cancelButton setTitleColor:[TYSearchBarAppearance appearance].cancelButtonHighlightColor forState:UIControlStateHighlighted];
            }
            if ([TYSearchBarAppearance appearance].cancelButtonDisableColor) {
                [_ty_cancelButton setTitleColor:[TYSearchBarAppearance appearance].cancelButtonDisableColor forState:UIControlStateDisabled];
            }
            if ([TYSearchBarAppearance appearance].cancelButtonFont) {
                _ty_cancelButton.titleLabel.font = [TYSearchBarAppearance appearance].cancelButtonFont;
            }
            if (self.delegate && [self.delegate respondsToSelector:@selector(ty_searchBarCancelButtonInitial)]) {
                [self.delegate ty_searchBarCancelButtonInitial];
            }
            // 如果回调中做了过多修改，直接算EdgeInsets会不准确，先重新布局一次比较合适
            [self setNeedsLayout];
            [self layoutIfNeeded];
            return;
        }
    }
    
    if (_ty_cancelButton && !UIEdgeInsetsEqualToEdgeInsets(_ty_cancelButtonInsets, UIEdgeInsetsZero)) {
        CGRect frame = _ty_cancelButton.frame;
        frame = UIEdgeInsetsInsetRect(frame, _ty_cancelButtonInsets);
        _ty_cancelButton.frame = frame;
    }
}

- (BOOL)isFirstResponder {
    return [super isFirstResponder] || [_ty_textField isFirstResponder];
}

#pragma mark - Accessor
- (UITextField *)ty_textField {
    if (!_ty_textField) {
        _ty_textField = [self valueForKey:kTYSearchBarTextFieldKVCKey];
        [self setupTextField];
        if (!_ty_textField) {
            [self setNeedsLayout];
            [self layoutIfNeeded];
            // 调用 layout 后，会执行 layoutsubviews 完成赋值，此处不需要再次赋值
        }
    }
    return _ty_textField;
}

- (BOOL)ty_isActive {
    return [self isFirstResponder];
}

- (void)setTYActive:(BOOL)active {
    [self becomeFirstResponder];
}

- (void)setTy_separatorColor:(UIColor *)color {
    if (!color) {
        [_separatorImageview removeFromSuperview];
        _separatorImageview = nil;
    } else {
        self.separatorImageview.backgroundColor = color;
    }
}
- (UIColor *)ty_seperatorColor {
    return self.ty_separatorColor;
}
- (void)setTy_seperatorColor:(UIColor *)ty_seperatorColor {
    self.ty_separatorColor = ty_seperatorColor;
}

- (UIImageView *)separatorImageview {
    if (!_separatorImageview) {
        _separatorImageview = [UIImageView new];
        [self addSubview:_separatorImageview];
        [_separatorImageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.mas_equalTo(self);
            make.height.mas_equalTo([TYSearchBarAppearance appearance].separatorHeight);
        }];
    }
    return _separatorImageview;
}

@end
